package cn.nfwx.tv.down.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

import cn.nfwx.tv.db.AppDatabase;
import cn.nfwx.tv.db.DownProgramDao;
import cn.nfwx.tv.db.DownProgramModel;
import cn.nfwx.tv.down.DownloadConstant;
import cn.nfwx.tv.down.DownloadStatus;
import cn.nfwx.tv.down.bean.DownloadInfo;
import cn.nfwx.tv.down.bean.RequestInfo;
import cn.nfwx.tv.down.config.InnerConstant;
import cn.nfwx.tv.down.execute.DownloadExecutor;
import cn.nfwx.tv.down.execute.DownloadTask;
import cn.nfwx.tv.down.utils.LogUtils;
import cn.nfwx.tv.helper.NetworkHelper;
import cn.nfwx.tv.util.SharePrefUtil;

public class DownloadProgramService extends Service {

    public static final String TAG = "DownloadService";

    public static boolean canRequest = true;

    //关于线程池的一些配置
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = 1;
    private static final int MAX_POOL_SIZE = 1;
    private static final long KEEP_ALIVE_TIME = 0L;

    private DownloadExecutor mExecutor;

    //存储任务
    private HashMap<String, DownloadTask> mTasks = new HashMap<>();

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mExecutor = new DownloadExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE,
                KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (null != intent && intent.hasExtra(InnerConstant.Inner.SERVICE_INTENT_EXTRA)) {
            try {
                ArrayList<RequestInfo> requesetes =
                        intent.getParcelableArrayListExtra(InnerConstant.Inner.SERVICE_INTENT_EXTRA);
                if (null != requesetes && requesetes.size() > 0) {
                    for (RequestInfo request : requesetes) {
                        if (request.getDictate() != InnerConstant.Request.refresh) {
                            executeDownload(request);
                        } else {
                            executeRefresh(request);
                        }
                    }
                }
            } catch (Exception e) {
                LogUtils.i(TAG, "onStartCommand()-> 接受数据,启动线程中发生异常");
                e.printStackTrace();
            }
        }
        return START_STICKY;
    }

    private void sendBroadcast(DownloadInfo info, DownProgramModel downProgram) {
        Intent intent = new Intent();
        intent.setAction(info.getAction());
        Bundle bundle = new Bundle();
        bundle.putParcelable(DownloadConstant.EXTRA_INTENT_DOWNLOAD, downProgram);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }

    /**
     * 更新数据库暂停状态
     *
     * @param requestInfo
     */
    private synchronized void executeRefresh(RequestInfo requestInfo) {
        DownloadInfo mDownloadInfo = requestInfo.getDownloadInfo();
        DownProgramDao downProgramDao = AppDatabase.getInstance(getBaseContext()).programDao();
        if (requestInfo.getDictate() == InnerConstant.Request.refresh) {
            if (!mTasks.containsKey(mDownloadInfo.getUniqueId())) {
                List<DownProgramModel> downProgramModels
                        = downProgramDao.queryAllByUrl(mDownloadInfo.getM3u8Url());
                if (!downProgramModels.isEmpty()) {
                    DownProgramModel downProgramModel = downProgramModels.get(0);
                    if (downProgramModel.getStats() != DownProgramModel.STATS_SUCCESS
                            && downProgramModel.getStats() != DownProgramModel.STATS_PAUSE) {
                        if (NetworkHelper.getInstance().hasConnection(this)) {
                            if (NetworkHelper.getInstance().isConnection4g(this)
                                    && !SharePrefUtil.getDownloadChoose(this)) {
                                downProgramModel.setStats(DownProgramModel.STATS_PAUSE);
                                downProgramDao.update(downProgramModel);
                            } else {
                                requestInfo.setDictate(InnerConstant.Request.loading);
                                executeDownload(requestInfo);
                            }
                        } else {
                            downProgramModel.setStats(DownProgramModel.STATS_PAUSE);
                            downProgramDao.update(downProgramModel);
                        }
                    }
                }
            }
        }
    }

    //Todo  除了简单的synchronized, 是否有更好的方式来进行加锁呢
    private synchronized void executeDownload(RequestInfo requestInfo) {
        DownloadInfo mDownloadInfo = requestInfo.getDownloadInfo();

        //先看看在任务列表里，是否有这个任务
        DownloadTask task = mTasks.get(mDownloadInfo.getUniqueId());
//        DownProgramDao downProgramDao = new DownProgramDao(getBaseContext());
//        TsProgramDao tsProgramDao = new TsProgramDao(getBaseContext());
        DownProgramDao downProgramDao = AppDatabase.getInstance(getBaseContext()).programDao();
        List<DownProgramModel> downProgramModels = downProgramDao.queryAllByUrl(mDownloadInfo.getM3u8Url());
        if (!downProgramModels.isEmpty()) {
            //DbHolder dbHolder = new DbHolder(getBaseContext());
            //FileInfo mFileInfo = dbHolder.getFileInfo(mDownloadInfo.getUniqueId());
            DownProgramModel downProgramModel = downProgramModels.get(0);
            if (downProgramModel.getStats() == DownProgramModel.STATS_SUCCESS) {
                sendBroadcast(mDownloadInfo, downProgramModel);
            } else {
                if (null == task) { //之前没有类似任务
                    //创建一个下载任务
                    if (requestInfo.getDictate() == InnerConstant.Request.loading) {
                        task = new DownloadTask(this, mDownloadInfo);
                        mTasks.put(mDownloadInfo.getUniqueId(), task);
                        mExecutor.executeTask(task);
                    } else if (requestInfo.getDictate() == InnerConstant.Request.pause) {
                        downProgramModel.setStats(DownProgramModel.STATS_PAUSE);
                        sendBroadcast(mDownloadInfo, downProgramModel);
                    }
                } else {
                    // 什么情况下, 可能存在这种这种状态
                    if (task.getStatus() == DownloadStatus.COMPLETE) {
                        mTasks.remove(mDownloadInfo.getUniqueId());
                        return;
                    }
                }

                if (null != task) {
                    if (requestInfo.getDictate() == InnerConstant.Request.loading) {
                        task.start();
                    } else if (requestInfo.getDictate() == InnerConstant.Request.pause) {
                        task.pause();
                        mExecutor.remove(task);
                        mTasks.remove(mDownloadInfo.getUniqueId());
                    }
                }
            }
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    @Override
    public void onDestroy() {
        for (Map.Entry<String, DownloadTask> e : mTasks.entrySet()) {
            DownloadTask task = e.getValue();
            task.pause();
            mExecutor.remove(task);
        }
        //DownProgramDao dao = new DownProgramDao(this);
        DownProgramDao dao = AppDatabase.getInstance(getBaseContext()).programDao();
        List<DownProgramModel> downProgramModels = dao.queryForAll();
        for (DownProgramModel downProgramModel : downProgramModels) {
            if (downProgramModel.getStats() != DownProgramModel.STATS_SUCCESS
                    && downProgramModel.getStats() != DownProgramModel.STATS_PAUSE) {
                downProgramModel.setStats(DownProgramModel.STATS_PAUSE);
                dao.update(downProgramModel);
            }
        }
        mExecutor.shutdown();
        mExecutor = null;
        super.onDestroy();
    }
}
